package cn.zxcoder.controller.SystemManage.module;

import cn.zxcoder.Tools.ToolUtil;
import cn.zxcoder.entity.SystemManage.Menu;
import cn.zxcoder.entity.Res;
import cn.zxcoder.service.IMenuService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zx
 * @since 2023-05-06
 */
@RestController
@Api(tags = "菜单中的修改和删除操作")
@RequestMapping("/api/Module")
public class MenuOpController {

    @Autowired
    IMenuService menuServiceIml;

    @ApiOperation("获通过id删除菜单")
    @DeleteMapping("/delete/{id}")
    @Transactional

    public Res moduleDelete(@PathVariable String id) {

        Menu one = menuServiceIml.getById(Integer.parseInt(id));
        ToolUtil.setMenuChildren(one,menuServiceIml);//设置出它的children属性
        int pid = one.getPid();
        boolean b = menuServiceIml.removeById(Integer.parseInt(id));
        List<Menu> children = one.getChildren();
        if (pid == 0 ) {//没有父级菜单的菜单（顶级菜单）
            if (children != null) {
                for (Menu child : children) {
                    menuServiceIml.removeById(child);
                }
            }
        } else {//有父级的菜单

            Menu parent = menuServiceIml.getById(pid);//父级菜单
            //找到去掉此菜单id的字符串字符索引
            String schildren = parent.getSchildren();
            int index = 0;
            char[] chars = schildren.toCharArray();
            for (int i = chars.length - 1; i >= 0; i--) {
                if (chars[i] == ',') {
                    index = i;
                    break;
                }
            }

            String res = schildren.substring(0, index);//删掉此菜单后的父级菜单字符串

            UpdateWrapper<Menu> wrapper = new UpdateWrapper<>();
            wrapper.set("schildren", res);
            wrapper.eq("id", pid);
             menuServiceIml.update(wrapper);
        }
        return new Res(b,null,b?"删除成功":"删除失败");
    }

    @ApiOperation("保存菜单信息")
    @PostMapping("/save")
    @Transactional

    public Res moduleSave(@RequestParam String parentId, @RequestParam String moduleName, @RequestParam String moduleIcon
            , @RequestParam Object moduleUrl,@RequestParam String moduleId,@RequestParam String moduleOrder, @RequestParam String token,@RequestParam boolean issave) {


        if (issave) {//正面是添加保存
            //创建新的菜单对象
            Menu menu = new Menu();
            menu.setIcon(moduleIcon);
            menu.setName(moduleName);
            menu.setMorder(Integer.parseInt(moduleOrder));
            menu.setPid(Integer.parseInt(parentId));
            menu.setAddTime(new Date());
            menu.setAddUser(token);

            if (parentId.equals("0")) {//此菜单是没有父级菜单的
                boolean save = menuServiceIml.save(menu);
                return new Res(save, null, save ? "保存成功" : "保存失败");

            } else {//此菜单是有父级菜单的
                menu.setUrl(String.valueOf(moduleUrl));
                boolean save = menuServiceIml.save(menu);
                //将此菜单对象和父级菜单关联起来
                //首先找到此菜单保存到数据库后的id
                QueryWrapper<Menu> wrapper = new QueryWrapper<>();
                wrapper.eq("name", moduleName);
                Menu one = menuServiceIml.getOne(wrapper);
                int id = one.getId();

                //设置数据库的schildren字段
                Menu parent = menuServiceIml.getById(Integer.parseInt(parentId));
                String schildren = parent.getSchildren();
                String sc = schildren==null||schildren.equals("")?""+id:schildren + "," + id;

                UpdateWrapper<Menu> wrapper2 = new UpdateWrapper<>();
                wrapper2.set("schildren", sc);
                wrapper2.eq("id", parentId);

                boolean update = menuServiceIml.update(wrapper2);
                return new Res(save && update, null, save && update ? "保存成功" : "保存失败");
            }

        } else {//证明是编辑
            UpdateWrapper<Menu> wrapper = new UpdateWrapper<>();

            wrapper.set("pid", parentId);
            wrapper.set("name", moduleName);
            wrapper.set("icon", moduleIcon);
            wrapper.set("url", moduleUrl);
            wrapper.set("morder", moduleOrder);
            wrapper.set("editUser", token);
            wrapper.set("editTime", new Date());
            wrapper.eq("id", moduleId);
            boolean update = menuServiceIml.update(wrapper);
            return new Res(update, null,update ? "保存成功" : "保存失败");
        }

    }

}
